<template>
  <el-dialog
    title="上传文件"
    :close-on-click-modal="false"
    @close="closeHandle"
    :visible.sync="visible">
    <el-upload
      drag
      action=""
      :before-upload="beforeUploadHandle"
      :http-request="uploadingHandle"
      style="text-align: center;">
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div class="el-upload__tip" slot="tip">只支持xlsx,xls格式的文件！</div>
    </el-upload>
  </el-dialog>
</template>

<script>
export default {
  data () {
    return {
      visible: false,
      url: '',
      file: new FormData(),
      fileList: [{name: '', url: ''}]
    }
  },
  methods: {
    init (id) {
      // this.url = this.$http.adornUrl(`/sys/oss/upload?token=${this.$cookie.get('token')}`)
      this.url = this.$http.adornUrl(`/post/upload`)
      this.visible = true
    },
    // 移除
    removeHandle (file, fileList) {
      console.log(file, fileList)
    },
    // 上传之前
    beforeUploadHandle (file) {
      if (file !== undefined) {
        let filetypename = file.name.substring(file.name.lastIndexOf('.'))
        if (filetypename === '.xlsx' || filetypename === '.xls') {
          this.file.append('file', file)
        } else {
          this.$message.error('只支持xlsx,xls格式的文件，请重新上传！')
          return false
        }
      }
    },
    // 上传操作
    uploadingHandle () {
      const data = this.file
      this.$http({
        url: this.url,
        method: 'post',
        data: data,
        header: {
          'Content-type': 'multipart/form-data'
        }
      }).then(res => {
        if (res.data.code === 0 && res.data) {
          this.$confirm('操作成功, 是否继续操作?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).catch(() => {
            this.visible = false
          })
        }
      })
    },

    // 上传成功
    successHandle (response, file, fileList) {
      this.fileList = fileList
      this.successNum++
      if (this.num === this.successNum) {
        this.$confirm('操作成功, 是否继续操作?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(() => {
          this.visible = false
        })
      }
      if (response && response.code === 0) {
        if (this.num === this.successNum) {
          this.$confirm('操作成功, 是否继续操作?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).catch(() => {
            this.visible = false
          })
        }
      } else {
        this.$message.error(response.msg)
      }
    },
    // 弹窗关闭时
    closeHandle () {
      this.fileList = []
      // this.$emit('refreshDataList')
    }
  }
}
</script>
